import React, { Component } from 'react'
import { Card } from 'antd'
import style from './index.module.scss'
import logo from 'assets/logo.png'
import { Form, Input, Button, Checkbox } from 'antd'
import { login } from 'api/users'
import { message } from 'antd'
import { setToken } from 'utils/storage'

export default class Login extends Component {
  state = {
    loding: false,
  }
  render() {
    return (
      <div className={style.login}>
        <Card className="login-container">
          <img src={logo} className="login-logo" alt="" />
          <Form
            size="large"
            onFinish={this.onFinish}
            initialValues={{
              mobile: '13911111111',
              code: '246810',
              agree: true,
            }}
          >
            <Form.Item
              name="mobile"
              validateTrigger="onBlur"
              rules={[
                { required: true, message: '手机号不能为空' },
                { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不对' },
              ]}
            >
              <Input placeholder="请输入手机号" autoComplete="OFF" />
            </Form.Item>

            <Form.Item
              validateTrigger="onBlur"
              name="code"
              rules={[
                {
                  pattern: /^\d{6}$/,
                  message: '验证码格式不对',
                },
                { required: true, message: '请输入验证码' },
              ]}
            >
              <Input placeholder="请输入验证码" autoComplete="OFF" />
            </Form.Item>

            <Form.Item
              name="agree"
              valuePropName="checked"
              rules={[
                {
                  validator(_, value) {
                    if (value) {
                      return Promise.resolve()
                    } else {
                      return Promise.reject('请同意协议')
                    }
                  },
                },
              ]}
            >
              <Checkbox>我已阅读并同意</Checkbox>
            </Form.Item>

            <Form.Item>
              <Button
                type="primary"
                htmlType="submit"
                block
                loading={this.state.loding}
              >
                登录
              </Button>
            </Form.Item>
          </Form>
        </Card>
      </div>
    )
  }
  onFinish = async ({ mobile, code }) => {
    this.setState({
      loding: true,
    })
    try {
      const res = await login({ mobile, code })
      setToken(res.data.token)
      message.success('登陆成功', 1, () => {
        // console.log(this.props)
        const { state } = this.props.location
        if (state) {
          this.props.history.push(state.from)
        } else {
          this.props.history.push('/home')
        }
      })
    } catch (e) {
      message.warning(
        e.response.data.message,
        1,
        this.setState({
          loding: false,
        })
      )
    }
  }
}
